//
//  JMWKWebView.m
//  Goin
//
//  Created by Lssyyy on 2019/7/31.
//  Copyright © 2019年 Goin. All rights reserved.
//

#import "JMWKWebView.h"
#import <WebKit/WebKit.h>
#import "WebViewJavascriptBridge.h"
#import "WKWebViewJavascriptBridge.h"
// WKWebView 内存不释放的问题解决
@interface WeakWebViewScriptMessageDelegate : NSObject<WKScriptMessageHandler>

//WKScriptMessageHandler 这个协议类专门用来处理JavaScript调用原生OC的方法
@property (nonatomic, weak) id<WKScriptMessageHandler> scriptDelegate;

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;

@end
@implementation WeakWebViewScriptMessageDelegate

- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
    self = [super init];
    if (self) {
        _scriptDelegate = scriptDelegate;
    }
    return self;
}

#pragma mark - WKScriptMessageHandler
//遵循WKScriptMessageHandler协议，必须实现如下方法，然后把方法向外传递
//通过接收JS传出消息的name进行捕捉的回调方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    if ([self.scriptDelegate respondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
        [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
    }
}
@end

@interface JMWKWebView()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic,strong) WKWebView *webView;
@property (nonatomic,strong) WKWebViewJavascriptBridge *wkBridge;
@end

@implementation JMWKWebView
#pragma mark - 懒加载
- (void)viewDidLoad {
    [super viewDidLoad];
//    [self initView];
}
#pragma mark -- WKUIDelegate
// 显示一个按钮。点击后调用completionHandler回调
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler();
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated {
   
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *userController = [[WKUserContentController alloc] init];
    configuration.userContentController = userController;
//    WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
    WKWebView* webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    webView.navigationDelegate = self;
    webView.UIDelegate = self;
    [self.view addSubview:webView];
    
   
    
    _wkBridge = [WKWebViewJavascriptBridge bridgeForWebView:webView];
     [_wkBridge setWebViewDelegate:self];
    [_wkBridge registerHandler:@"testObjcCallback" handler:^(id data, WVJBResponseCallback responseCallback) {
         NSString *kkk = [data objectForKey:@"foo"];
        NSLog(@"testObjcCallback called: %@===%@", data,kkk);
        responseCallback(@"调用OC且返回了参数XXX");
    }];
    [_wkBridge registerHandler:@"getVersionName" handler:^(id data, WVJBResponseCallback responseCallback) {

        NSLog(@"一个数字: %@",data);
        NSLog(@"调用了版本号: %@", data);
        responseCallback(@"2.1.4");
    }];
//
    [self loadExamplePage:webView];
}
- (void)loadExamplePage:(WKWebView*)webView {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
    [webView loadRequest:request];
}

- (void)deleteWebCache {
    //allWebsiteDataTypes清除所有缓存
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
    
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        
    }];
}


- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    NSLog(@"网页开始加载");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSLog(@"网页结束加载");
    //OC调用JS
//    [_wkBridge callHandler:@"testJavascriptHandler" data:@{ @"h啊啊啊啊":@"测试" }];
    //data是本地传给JS的参数 responseData是JS返回给本地的参数 keyvalue形式
    [_wkBridge callHandler:@"testJavascriptHandler" data:@{ @"h啊啊啊啊":@"测试" } responseCallback:^(id responseData) {
          NSLog(@"调用JS方法成功%@",responseData);
    }];
    NSString *locationStr = @{@"longitude": @"122.1111",
                              @"latitude": @"66.555"}.jsonStringEncoded;
    [_wkBridge callHandler:@"iosOpenPosition" data:locationStr responseCallback:^(id responseData) {
        NSLog(@"调用JS方法成功%@",responseData);
    }];
}
#pragma mark - action

- (void)pushToStoreVC:(NSString *)storeId {
    
}

- (void)locationUpdate {
    [self.webView reload];
}
@end
